<?php

/**
 * Mcrypt plugin, set a key before use it
 * 
 */
class Mcrypt
{
	protected $cipher;
	protected $mode;
	protected $hander;
	protected $initVector;
	
    /**
     * Constuctor
     * @param array $data
     */
    public function __construct(array $data=array())
    {
    }

    /**
     * Initialize mcrypt module
     * @param string $key cipher private key
     * @return Mcrypt
     */
    public function init($key)
    {
        if (!$this->cipher ) {
            $this->cipher= MCRYPT_BLOWFISH;
        }

        if (!$this->mode ) {
            $this->mode = MCRYPT_MODE_ECB;
        }

        $this->handler= mcrypt_module_open($this->cipher , '', $this->mode, '');

        if (!$this->initVector ) {
            if (MCRYPT_MODE_CBC == $this->mode) {
                $this->initVector= substr(
                    md5( mcrypt_create_iv (mcrypt_enc_get_iv_size($this->handler), MCRYPT_RAND) ),
                    - mcrypt_enc_get_iv_size($this->handler )
                );
            } else {
                $this->initVector= mcrypt_create_iv (mcrypt_enc_get_iv_size($this->handler), MCRYPT_RAND);
            }
        }

        $maxKeySize = mcrypt_enc_get_key_size($this->handler);

        if (strlen($key) > $maxKeySize) { // strlen() intentionally, to count bytes, rather than characters
            $this->handler= null;
            throw new Exception('Maximum key size must be smaller '.$maxKeySize);
        }

        mcrypt_generic_init($this->handler, $key, $this->initVector);
        return $this;
    }

    /**
     * Encrypt data
     *
     * @param string $data source string
     * @return string
     */
    public function encrypt($data)
    {
        if (!$this->handler) {
            throw new Exception('Crypt module is not initialized.');
        }
        if (strlen($data) == 0) {
            return $data;
        }
        return mcrypt_generic($this->handler, $data);
    }

    /**
     * Decrypt data
     *
     * @param string $data encrypted string
     * @return string
     */
    public function decrypt($data)
    {
        if (!$this->handler) {
            throw new Exception('Crypt module is not initialized.');
        }
        if (strlen($data) == 0) {
            return $data;
        }
        return mdecrypt_generic($this->handler, $data);
    }

    /**
     * Desctruct cipher module
     *
     */
    public function __destruct()
    {
        if ($this->handler) {
            $this->_reset();
        }
    }

    protected function _reset()
    {
        mcrypt_generic_deinit($this->handler);
        mcrypt_module_close($this->handler);
    }
}
